package cn.xiaopengstack.domain.agent.service.armory.node;

import cn.bugstack.wrench.design.framework.tree.StrategyHandler;
import cn.xiaopengstack.domain.agent.model.entity.ArmoryCommandEntity;
import cn.xiaopengstack.domain.agent.model.valobj.AiAgentEnumVO;
import cn.xiaopengstack.domain.agent.model.valobj.AiClientToolMcpVO;
import cn.xiaopengstack.domain.agent.service.armory.AbstractArmorySupport;
import cn.xiaopengstack.domain.agent.service.armory.factory.DefaultArmoryStrategyFactory;
import com.alibaba.fastjson.JSONObject;
import io.modelcontextprotocol.client.McpSyncClient;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author jiangyangang
 * MCP工具组装注册节点
 */
@Component
@Slf4j
public class AiClientToolMcpNode extends AbstractArmorySupport {
    @Resource
    private AiClientModelNode aiClientModelNode;

    @Override
    protected String beanName(String id) {
        return AiAgentEnumVO.AI_CLIENT_TOOL_MCP.getBeanNameTag() + id;
    }

    @Override
    protected String dataName() {
        return AiAgentEnumVO.AI_CLIENT_TOOL_MCP.getDataName();
    }

    @Override
    protected String doApply(ArmoryCommandEntity requestParameter, DefaultArmoryStrategyFactory.DynamicContext dynamicContext) throws Exception {
        List<AiClientToolMcpVO> mcps = dynamicContext.getValue(dataName());
        if (CollectionUtils.isEmpty(mcps)) {
            log.info("AI客户端加载，无可加载的AI MCP工具...");
            return router(requestParameter, dynamicContext);
        }

        log.info("AI客户端加载，MCP工具加载中【{}】", JSONObject.toJSONString(mcps.stream().map(mcp -> {return  mcp.getMcpId() + "_" + mcp.getMcpName();}).collect(Collectors.joining(","))));
        for (AiClientToolMcpVO mcpVO : mcps) {
            McpSyncClient mcpClient = getMcpClient(mcpVO);
            registerBean(beanName(mcpVO.getMcpId()), McpSyncClient.class, mcpClient);
        }

        return router(requestParameter, dynamicContext);
    }



    @Override
    public StrategyHandler<ArmoryCommandEntity, DefaultArmoryStrategyFactory.DynamicContext, String> get(ArmoryCommandEntity requestParameter, DefaultArmoryStrategyFactory.DynamicContext dynamicContext) throws Exception {
        return aiClientModelNode;
    }
}
